#include "DictionaryUserParser.h"

#include "UnitsParser.h"
#include "EntryUserParser.h"

#include <QXmlStreamReader>
#include <QString>

namespace Ipc2581b
{

DictionaryUserParser::DictionaryUserParser(
    UnitsParser *&_unitsParser
    , EntryUserParser *&_entryUserParser
):    m_unitsParser(_unitsParser)
    , m_entryUserParser(_entryUserParser)
{

}

bool DictionaryUserParser::parse(QXmlStreamReader *reader)
{
    /* Pre */

    m_result.reset(new DictionaryUser());

    /* Attributes */

    QStringRef data;
    if (reader->attributes().hasAttribute(QStringLiteral("units")))
    {
        data = reader->attributes().value(QStringLiteral("units"));
        if (!m_unitsParser->parse(reader, data))
            return false;
        m_result->units = m_unitsParser->result();
    }
    else
    {
        reader->raiseError(QStringLiteral("units: Attribute is required"));
        return false;
    }

    /* Elements */

    while (reader->readNextStartElement())
    {
        auto name = reader->name();
        if (name == QStringLiteral("EntryUser"))
        {
            if (!m_entryUserParser->parse(reader))
                return false;
            auto result = m_entryUserParser->result();
            m_result->entryUserList.append(result);
        }
        else
            reader->skipCurrentElement();
    }

    /* Post */

    // TODO: Check multiplicity of elements/attributes

    return true;
}

DictionaryUser *DictionaryUserParser::result()
{
    return m_result.take();
}

}